#include <iostream>
#include <unistd.h>
#include "test.hpp"
#include"LockGuard.hpp"
using namespace std;

pthread_mutex_t mtx;
int tickets = 1000;

void *ThreadRoutine(void *args)
{
    int sum = 0;
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        {
            // 进入临界区，准备加锁
            LockGuard guard(&mtx);
            if (tickets > 0)
            {
                usleep(2000);
                sum++;
                --tickets;
            }
            else
                break;
        }
        usleep(2000);
    }

    {
        LockGuard guard(&mtx);
        cout<<"线程"<<name<<"抢票完成，最终票数为："<<sum<<endl;
    }
}

int main()
{

    //创建互斥锁
    pthread_mutex_init(&mtx,nullptr);
    
    //创建线程
    Thread t1(1,ThreadRoutine,(void*)"thread-1");
    Thread t2(2,ThreadRoutine,(void*)"thread-2");
    Thread t3(3,ThreadRoutine,(void*)"thread-3");

    //运行
    t1.run();
    t2.run();
    t3.run();

    //等待
    t1.join();
    t2.join();
    t3.join();
    //销毁互斥锁
    pthread_mutex_destroy(&mtx);

    cout<<"剩余票数"<<tickets<<endl;

    return 0;
}